<template>
  <div class="home">
    <meta name="keywords" content="电商,购物,商城" />
    <!-- 头部 -->
    <div class="head">
      <div class="content">
        <nuxt-link to="/" class="logo">
          <img
            class="logo-img"
            v-if="webConfigData.pcLogoImgText"
            :src="webConfigData.pcLogoImgText"
          />
          <!-- <img style="width: 140px; height: auto;" class="logo-img" v-if="webConfigData.pcLogoImgText" src="../assets/images/logo.png"/> -->
          <!-- <text >湖南洛云网络科技有限公司</text> -->
          <!-- <img style="height: 38px;width: 160px;" class="logo-img" v-if="webConfigData.pcLogoImgText" src="../assets/images/register-logo.png"/> -->
          <div class="name">
            <span class="cn">沙鲜送</span>
            <span class="en">Sha Xian Song</span>
          </div>
        </nuxt-link>
        <div
          :class="['menu', this.$store.state.locale == 'en' ? 'menu-en' : '']"
        >
          <nuxt-link to="/" class="item item-on">{{
            $t('commonHead.home')
          }}</nuxt-link>
          <nuxt-link class="item" to="/list?st=0">{{
            $t('commonHead.productList')
          }}</nuxt-link>
          <nuxt-link class="item" to="/list?st=1">{{
            $t('commonHead.newProducts')
          }}</nuxt-link>
          <nuxt-link class="item" to="/special-discount">{{
            $t('commonHead.limitedTimeOffer')
          }}</nuxt-link>
          <nuxt-link class="item" to="/group-buy">{{
            $t('commonHead.groupDiscount')
          }}</nuxt-link>
          <nuxt-link class="item" to="/flash-sale">{{
            $t('commonHead.spikeSpecial')
          }}</nuxt-link>
          <a class="item" href="javascript:void(0)" @click="toCoupons">{{
            $t('commonHead.voucherCenter')
          }}</a>
          <nuxt-link class="item" to="/user-center/xt-index"
            >协同采购</nuxt-link
          >
        </div>

        <div class="search">
          <input
            type="text"
            class="search-input"
            :placeholder="$t('searchByStOrpN')"
          />
          <input type="submit" class="search-btn" value="搜索" />
        </div>
      </div>
    </div>
    <!-- /头部 -->
    <!-- 下滑时候的头部 -->
    <transition name="fade">
      <div v-if="showHeadScroll" class="head-scroll">
        <div class="content" style="padding-left: 140px">
          <nuxt-link to="/" class="logo">
            <!-- <img class="logo-img" v-if="webConfigData.pcLogoImgText" :src="webConfigData.pcLogoImgText"/> -->
            <div class="name">
              <span class="cn">沙鲜送</span>
              <span class="en">Sha Xian Song</span>
            </div>
          </nuxt-link>
          <div
            :class="['menu', this.$store.state.locale == 'en' ? 'menu-en' : '']"
          >
            <nuxt-link class="item item-on" to="/">{{
              $t('commonHead.home')
            }}</nuxt-link>
            <nuxt-link to="/list?st=0" class="item">{{
              $t('commonHead.productList')
            }}</nuxt-link>
            <nuxt-link to="/list?st=1" class="item">{{
              $t('commonHead.newProducts')
            }}</nuxt-link>
            <nuxt-link to="/special-discount" class="item">{{
              $t('commonHead.limitedTimeOffer')
            }}</nuxt-link>
            <nuxt-link to="/group-buy" class="item">{{
              $t('commonHead.groupDiscount')
            }}</nuxt-link>
            <nuxt-link to="/flash-sale" class="item">{{
              $t('commonHead.spikeSpecial')
            }}</nuxt-link>
            <!-- <nuxt-link to="/coupons" class="item">领券中心</nuxt-link> -->
            <a href="javascript:void(0)" class="item" @click="toCoupons">{{
              $t('commonHead.voucherCenter')
            }}</a>
          </div>
          <div class="right">
            <div class="search">
              <input
                type="text"
                v-model="topsearchTerms"
                @keyup.enter="topSearchProd"
                class="search-input"
                :placeholder="$t('searchByStOrpN')"
              />
              <input
                type="submit"
                @click="topSearchProd"
                class="search-btn"
                value="搜索"
              />
            </div>
            <div class="scroll-cart" @click="toCart">
              <span class="number" v-if="totalCartCount">{{
                totalCartCount > 99 ? '99+' : totalCartCount
              }}</span>
            </div>
          </div>
        </div>
      </div>
    </transition>
    <!-- 下滑时候的头部 -->

    <!-- 分类筛选 -->
    <CategroySidebar />
    <!-- /分类筛选 -->

    <!-- banner -->
    <div class="banner">
      <el-carousel height="450px" style="overflow-y: hidden">
        <el-carousel-item
          v-for="(item, index) in banners"
          :key="index"
          style="cursor: pointer"
          class="banner-item"
        >
          <img
            :src="item.imgUrl"
            style="width: 100%; height: 100%"
            @click="imgToProd(banner)"
          />
        </el-carousel-item>
      </el-carousel>
    </div>
    <!-- /banner -->

    <!-- 搜索 -->
    <div class="home-search">
      <div class="hot-word">
        <div
          class="tit"
          :style="
            this.$store.state.locale == 'en' ? 'width:95px;' : 'width:75px;'
          "
        >
          {{ $t('index.popularSearches') }}：
        </div>
        <div :class="['con', this.$store.state.locale == 'en' ? 'con-en' : '']">
          <span
            :title="hot.title"
            class="item"
            v-for="(hot, index) in hotSearchList"
            :key="index"
            @click="onHistSearch(hot.title)"
            >{{ hot.title }}</span
          >
        </div>
      </div>
      <div class="search-msg" onselectstart="return false">
        <div class="search-input-box">
          <input
            type="text"
            class="search-input"
            v-model="searchTerms"
            @keyup.enter="toSearchProdPage"
            :placeholder="$t('searchByStOrpN')"
          />
          <div class="select-search" @click="selectChoose">
            {{ searchItem }}
          </div>
          <ul class="select-list" v-if="showSelectItem">
            <li class="select-item" @click="selectSearchItem(0)">
              {{ $t('index.prod') }}
            </li>
            <li class="select-item" @click="selectSearchItem(1)">
              {{ $t('index.shop') }}
            </li>
          </ul>
        </div>
        <input
          type="submit"
          class="search-btn"
          :value="$t('index.search')"
          @click="toSearchProdPage"
          :style="$t('language') == 'en' ? '' : 'letter-spacing: 2px;'"
        />
      </div>
      <div class="cart-btn" @click="toCart">
        {{ $t('index.shoppingCart') }}
        <span class="number" v-if="totalCartCount">{{
          totalCartCount > 99 ? '99+' : totalCartCount
        }}</span>
      </div>
    </div>
    <!-- /搜索 -->

    <div class="content">
      <!-- 快捷入口 -->
      <div class="shortcut" v-if="false">
        <div class="item item01">
          <div class="text">
            <div class="cn">{{ $t('index.newProduct') }}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-01.png" alt />
          </div>
        </div>
        <div class="item item02">
          <div class="text">
            <div class="cn">{{ $t('index.limitedTimeOffer') }}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-02.png" alt />
          </div>
        </div>
        <div class="item item03">
          <div class="text">
            <div class="cn">{{ $t('index.groupDiscount') }}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-03.png" alt />
          </div>
        </div>
        <div class="item item04">
          <div class="text">
            <div class="cn">{{ $t('index.specialSale') }}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-04.png" alt />
          </div>
        </div>
        <div class="item item05">
          <div class="text">
            <div class="cn">{{ $t('index.couponsCenter') }}</div>
          </div>
          <div class="img">
            <img src="~/assets/img/short-05.png" alt />
          </div>
        </div>
      </div>

      <!-- 广告 -->
      <nuxt-link to="/flash-sale" class="adv" v-if="snapUpList.length">
        <img src="~/assets/img/adv1.jpg" alt />
      </nuxt-link>

      <!-- 秒杀专区 -->
      <div class="goods-list flash-sale" v-if="snapUpList.length">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{ $t('index.secondKillZone') }}</span>
            <span class="description">{{
              $t('index.selectedProductsLimited')
            }}</span>
          </div>
          <nuxt-link to="/flash-sale" class="view-more">
            {{ $t('index.seeMore') }}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ProdItem :pale-list="snapUpList" />
      </div>

      <!-- 广告 -->
      <nuxt-link to="/group-buy" class="adv" v-if="composeGroup.length">
        <img src="~/assets/img/adv2.jpg" alt />
      </nuxt-link>

      <!-- 优惠团购 -->
      <div class="goods-list group-list" v-if="composeGroup.length">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{ $t('index.groupDiscount') }}</span>
            <span class="description">{{
              $t('index.recommendGoodThings')
            }}</span>
          </div>
          <nuxt-link to="/group-buy" class="view-more">
            {{ $t('index.seeMore') }}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ProdItem :pale-list="composeGroup" />
      </div>

      <!-- 广告 -->
      <nuxt-link to="/list" class="adv" v-if="hotSalesList.records.length">
        <img src="~/assets/img/adv3.jpg" alt />
      </nuxt-link>

      <!-- 商城热销 -->
      <div class="goods-list group-list" v-if="hotSalesList.records.length">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{ $t('index.hotSale') }}</span>
            <span class="description">{{
              $t('index.wordGoodiesInfiniteRepurchase')
            }}</span>
          </div>
          <nuxt-link to="/list?st=0" class="view-more">
            {{ $t('index.seeMore') }}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ProdItem :pale-list="hotSalesList.records" />
      </div>

      <!-- 广告 -->
      <!-- <nuxt-link to="/shopList" class="adv"> -->
      <nuxt-link to="/list?st=0" class="adv">
        <img src="~/assets/img/adv4.jpg" alt />
      </nuxt-link>

      <!-- 优选好店 -->
      <div class="goods-list shop-list">
        <div class="list-tit">
          <div class="text">
            <span class="tit">{{ $t('index.preferredStores') }}</span>
            <span class="description">{{
              $t('index.recommendGoodThingsTogetherWithTheGroup')
            }}</span>
          </div>
          <!-- <nuxt-link to="/shopList" class="view-more"> -->
          <nuxt-link to="/list?st=0" class="view-more">
            {{ $t('index.seeMore') }}
            <span class="arrow">></span>
          </nuxt-link>
        </div>
        <ShopItem :shop-list="hotShopList" />
      </div>
      <!-- /优选好店 -->
    </div>
    <!-- 登录弹窗组件 -->
    <LoginPopup v-if="showLogin" v-on:hideLoginPop="hideLoginPop" />
    <!-- /登录弹窗组件 -->
  </div>
</template>

<script>
import Cookie from 'js-cookie'
import LoginPopup from '~/components/login-popup'
import ProdItem from '~/components/prod-item'
import ShopItem from '~/components/shop-item'
import CategroySidebar from '~/components/categroy-sidebar'
import util from '~/plugins/util'
export default {
  layout: 'home',
  components: {
    ProdItem,
    ShopItem,
    CategroySidebar,
    LoginPopup,
  },
  //在页面加载之前先加载数据
  async asyncData({ app, query }) {
    let [
      requestWebConfigData,
      requestSnapUp,
      requestTeamBuy,
      requestHotSales,
      requestHotShops,
    ] = await Promise.all([
      app.$axios.get('/webConfig/getPcWebConfig'), //网站配置信息
      app.$axios.get('/seckill/indexList'), //秒杀
      app.$axios.get('/groupProd/indexList'), //团购
      app.$axios.get('/search/searchProdPage', {
        params: {
          current: 1,
          size: 12,
          sort: 1,
          orderBy: 1,
        },
      }), //热销
      app.$axios.get('/shop/hotShops'), //好店
    ])
    //秒杀处理
    let snapUpResult = requestSnapUp.data
      .filter(
        (item) => util.dateToTimestamp(item.endTime) > new Date().getTime()
      )
      .slice(0, 4) //过滤掉秒杀时间已结束的商品
    let groupResult = requestTeamBuy.data.slice(0, 4) //过滤掉秒杀时间已结束的商品
    return {
      snapUpList: snapUpResult, //秒杀
      composeGroup: groupResult, //团购
      hotSalesList: requestHotSales.data, //热销
      hotShopList: requestHotShops.data, //好店
      webConfigData: requestWebConfigData.data, //网站配置信息
    }
  },

  data() {
    return {
      showLogin: false,
      showHeadScroll: false, //头部显隐
      banners: [], //轮播图
      hotSearchList: [], //热搜
      snapUpList: [], //秒杀专场
      composeGroup: [], //优惠团购
      hotSalesList: [], //商城热销
      current: 1,
      size: 10,
      sort: 1,
      orderBy: 1,
      showSelectItem: false, //搜索下拉选择框显隐
      searchItem: this.$t('index.prod'), //搜索下拉框选择店铺或商品
      searchTerms: '', //搜索词
      topsearchTerms: '', //上滑头部搜索词
      hotShopList: [], //优选好店
      searchType: 0, //搜索类型 0商品 1店铺
      totalCartCount: 0, // 购物车总数量
      webConfigData: {}, //网站配置信息
      language: this.$store.state.locale,
    }
  },
  mounted() {
    // 缓存到本地
    localStorage.setItem('webConfig', JSON.stringify(this.webConfigData))
    // 设置网页标题文本和图标
    document.title = this.webConfigData.pcTitleContentCn || ''
    // document.title = '沙鲜送' || ''
    // this.changeFavicon(this.webConfigData.pcTitleImg)
    // 监听页面滚动
    window.addEventListener('scroll', this.scrollToTop)
    //轮播图
    this.getIndexBanner()
    //热搜
    this.getHotSearch(this.searchType)
    //优选好店
    this.getHotShopsHead()
    // 获取购物车数量
    this.getCartCount()
  },
  watch: {},
  methods: {
    /**
     * 获取购物车商品总数
     */
    getCartCount() {
      if (Cookie.get('token')) {
        this.$axios.get('/p/shopCart/prodCount').then(({ data }) => {
          this.totalCartCount = data
          this.$store.commit('cartNumber/changeCartNumber', data)
        })
      }
    },
    /**
     * 页面滚动事件
     */
    scrollToTop() {
      let scrollTop =
        window.pageYOffset ||
        document.documentElement.scrollTop ||
        document.body.scrollTop
      this.showHeadScroll = scrollTop > 90 ? true : false
    },
    /**
     * 领券中心
     */
    toCoupons() {
      // if (Cookie.get('token')) {
      //   console.log('token1:',Cookie.get('token'))
      //   this.$router.push({ path: '/coupons' })
      // } else {
      //   console.log('token2:',Cookie.get('token'))
      //   this.showLogin = true
      // }
      this.$router.push({ path: '/coupons' })
    },
    /**
     * 隐藏登录弹窗
     */
    hideLoginPop() {
      this.showLogin = false
    },
    /**
     * 轮播图
     */
    getIndexBanner() {
      this.$axios
        .get('/indexImgs/0', {
          params: {
            imgType: 1,
          },
        })
        .then(({ data }) => {
          this.banners = data
        })
    },
    /**
     * 热搜词
     */
    getHotSearch() {
      let url = this.searchType ? '/shop/hotShops' : '/search/hotSearch'
      this.$axios
        .get(url, {
          params: {
            number: 4,
            sort: 0,
          },
        })
        .then(({ data }) => {
          if (this.searchType) {
            this.hotSearchList = []
            for (let i = 0; i < (data.length > 6 ? 6 : data.length); i++) {
              let shoInfo = {
                title: data[i].shopName,
                hotSearchId: data[i].shopId,
              }
              this.hotSearchList.push(shoInfo)
            }
          } else {
            this.hotSearchList = data
          }
        })
    },
    /** 搜索框选择 */
    selectChoose() {
      this.showSelectItem = !this.showSelectItem
    },
    /** 点击选择 店铺 || 商品 */
    selectSearchItem(sts) {
      if (sts === 0) {
        this.searchItem = this.$t('index.prod')
        this.showSelectItem = false
        this.searchType = 0 //商品
      } else if (sts === 1) {
        this.searchItem = this.$t('index.shop')
        this.showSelectItem = false
        this.searchType = 1 //店铺
      }

      this.getHotSearch()
    },

    /**
     * 搜索
     */
    toSearchProdPage() {
      var searchType = this.searchType
      var searchTerms = this.searchTerms.trim() //去除字符串的头尾空格
      if (searchType == 0) {
        if (!searchTerms) {
          this.$message({
            message: this.$t('commonHead.productNameCannotBeEmpty'),
            type: 'error',
            duration: 1000,
          })
          return
        }
        // 跳转到商品列表页
        this.$router.push({ path: '/list?pn=' + searchTerms })
      } else if (searchType == 1) {
        if (!searchTerms) {
          this.$message({
            message: this.$t('commonHead.storeNameCannotBeEmpty'),
            type: 'error',
            duration: 1000,
          })
          return
        }
        // 跳转到店铺列表页
        this.$router.push({ path: '/shopList?shopName=' + searchTerms })
      }
    },
    topSearchProd() {
      var searchTerms = this.topsearchTerms.trim() //去除字符串的头尾空格
      if (!searchTerms) {
        this.$message({
          message: this.$t('commonHead.productNameCannotBeEmpty'),
          type: 'error',
          duration: 1000,
        })
        return
      }
      // 跳转到商品列表页
      this.$router.push({ path: '/list?pn=' + searchTerms })
    },
    /**
     * 点击热搜词搜索商品
     */
    onHistSearch(name) {
      this.searchTerms = name
      // this.searchType = 1
      this.toSearchProdPage()
    },

    /**
     * 商城热销
     */
    // getHotSalesProds () {
    //   this.$axios.get('/search/searchProdPage', {
    //     params: {
    //       current: this.current,
    //       size: 12,
    //       sort: 1,
    //       orderBy: 1
    //     }
    //   }).then(({ data }) => {
    //     this.hotSalesList = data.records
    //   })
    // },
    /**
     * 优选好店
     */
    getHotShopsHead() {
      this.$axios.get('/shop/hotShops').then(({ data }) => {
        this.hotShopList = data
      })
    },

    /**
     * 跳转购物车页面
     */
    toCart() {
      this.$router.push('/cart')
    },
    /**
     * 轮播图跳转到商品
     */
    imgToProd(banner) {
      if (banner.type !== 0) {
        return
      }
      const prodId = banner.relation
      this.$axios
        .get('/prod/isStatus', {
          params: {
            prodId: prodId,
          },
        })
        .then(({ data }) => {
          if (data) {
            this.$router.push({
              name: 'detail-prodId',
              params: { prodId: prodId, bannerEnter: '1' },
            })
          }
        })
    },
    changeFavicon(link) {
      let favicon = document.querySelector('link[rel="icon"]')
      if (favicon !== null) {
        favicon.href = link
      } else {
        favicon = document.createElement('link')
        favicon.rel = 'icon'
        favicon.href = link
        document.head.appendChild(favicon)
      }
    },
  },
  destroyed() {
    // 页面销毁时移除监听
    window.removeEventListener('scroll', this.handleScroll)
  },
}
</script>

<style scoped src='~/assets/css/home.css'></style>
